# coding: utf-8
# @Author: 莫小鱼
import re
import requests
from AutoApiTest.unit_tools.handle_data.yaml_handler import read_yaml, write_yaml
from AutoApiTest.unit_tools.log_util import logs


class SendRequests:

    def __init__(self):
        pass

    @classmethod
    def _text_encode(cls, res_text):
        """
        处理接口返回值出现uicode编码问题：如:\\u797b
        :param res_text:
        :return:
        """
        match = re.search(r"\\u[0-9a-fA-F]{4}", res_text)
        if match:
            result = res_text.encode().decode('unicode_escape')
        else:
            result = res_text
        return result

    def send_request(self, **kwargs):
        # 创建一个会话
        session = requests.Session()
        response = None

        try:

            response = session.request(**kwargs)
            set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
            if set_cookie:
                # print(f"获取到cookie:{set_cookie}")
                write_yaml({'Cookie': set_cookie})
            result = self._text_encode(response.text)
            print(result)
        except requests.exceptions.ConnectionError:
            logs.error("接口请求异常，可能是request的连接数太多")
        except requests.exceptions.RequestException as e:
            logs.error(f"请求异常，请检查系统或数据是否正常!:{e}")

        return response

    def execute_api_request(self, api_name,
                            url, method, headers,
                            case_name, cookie=None,
                            files=None, **kwargs):
        """
        发起接口请求
        :param api_name: 接口名称
        :param url: 接口地址
        :param method: 请求方法
        :param headers: 请求头
        :param case_name: 测试用例名称
        :param cookie: 请求cookies
        :param file: 文件上传
        :param kwargs: 未知数量的关键字参数
        :return:
        """
        response = self.send_request(method=method,
                                     url=url,
                                     headers=headers,
                                     cookies=cookie,
                                     files=files,
                                     timeout=10,
                                     verify=False,
                                     **kwargs)
        return response


if __name__ == '__main__':
    from AutoApiTest.unit_tools.handle_data.configParse import ConfigParse

    host = ConfigParse().get_host('host')
    data = read_yaml('../data/login.yaml')[0]
    print(data)
    url = host + data['baseInfo']['api_url']
    print(url)
    method = data['baseInfo']['method']
    print(method)
    headers = data['baseInfo']['headers']
    print(headers)

    req_data = data['testCase']
    print(req_data)
    casename = data['testCase'][0]['casename']
    print(casename)
    post_data = data['testCase'][0]['data']
    print(post_data)

    send = SendRequests()
    res = send.execute_api_request(api_name=None, url=url, method=method,
                                   headers=None, case_name=None,
                                   data=post_data)
    print(res)
    token = res.json()['token']
    print(token)
    user_id = res.json()['userId']
    print(user_id)
    write_yaml({'token': token, 'userId': user_id})
